package com.lyc.kotlin.wanandroid.uis.activitys

import android.annotation.SuppressLint
import android.content.Intent
import android.os.Bundle
import android.util.Log
import android.view.View
import android.view.ViewGroup
import android.widget.Toast
import androidx.core.view.GravityCompat
import androidx.fragment.app.FragmentTransaction
import com.google.android.material.bottomnavigation.BottomNavigationView
import com.lyc.kotlin.wanandroid.R
import com.lyc.kotlin.wanandroid.base.BaseActivity
import com.lyc.kotlin.wanandroid.uis.fragments.HomeFragment
import com.lyc.kotlin.wanandroid.uis.fragments.KnowledgeTreeFragment
import com.lyc.kotlin.wanandroid.uis.fragments.NavigationFragment
import com.lyc.kotlin.wanandroid.uis.fragments.ProjectFragment
import com.mikepenz.crossfadedrawerlayout.view.CrossfadeDrawerLayout
import com.mikepenz.materialdrawer.AccountHeader
import com.mikepenz.materialdrawer.AccountHeaderBuilder
import com.mikepenz.materialdrawer.Drawer
import com.mikepenz.materialdrawer.DrawerBuilder
import com.mikepenz.materialdrawer.interfaces.ICrossfader
import com.mikepenz.materialdrawer.model.PrimaryDrawerItem
import com.mikepenz.materialdrawer.model.ProfileDrawerItem
import com.mikepenz.materialdrawer.model.SecondaryDrawerItem
import com.mikepenz.materialdrawer.model.SectionDrawerItem
import com.mikepenz.materialdrawer.model.interfaces.IDrawerItem
import com.mikepenz.materialdrawer.model.interfaces.Nameable
import com.mikepenz.materialdrawer.util.DrawerUIUtils
import com.mikepenz.materialize.util.UIUtils
import kotlinx.android.synthetic.main.activity_main.*

class MainActivity : BaseActivity() {
    private val FRAGMENT_HOME = 1
    private val FRAGMENT_NAVIGATION = 2
    private val FRAGMENT_KNOWLEDGE = 3

    private val FRAGMENT_PROJECT = 4


    private val BOTTOM_INDEX: String = "bottom_index"

    private var mIndex = FRAGMENT_HOME

    private lateinit var headerResult: AccountHeader
    private lateinit var result: Drawer
    private lateinit var crossfadeDrawerLayout: CrossfadeDrawerLayout

    private var mHomeFragment: HomeFragment? = null
    private var mKnowledgeTreeFragment: KnowledgeTreeFragment? = null
    private var mNavigationFragment: NavigationFragment? = null
    private var mProjectFragment: ProjectFragment? = null

    override fun useEventBus(): Boolean = true

    override fun attachLayoutRes(): Int = R.layout.activity_main

    override fun start() {

    }

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        val profile = ProfileDrawerItem().withName("Mike Penz").withIcon(R.mipmap.ic_launcher).withEnabled(false)

        headerResult = AccountHeaderBuilder()
                .withActivity(this)
                .withTranslucentStatusBar(true)
                .addProfiles(
                        profile
                )
                .build()

        result = DrawerBuilder()
                .withActivity(this)
                .withToolbar(toolbar)
                .withHasStableIds(true)
                .withDrawerLayout(R.layout.crossfade_drawer)
                .withDrawerWidthDp(72)
                .withAccountHeader(headerResult)
                .addDrawerItems(
                        PrimaryDrawerItem().withName(getString(R.string.me)).withIcon(R.drawable.ic_me_black_24dp).withIdentifier(1).withSelectable(false),
                        PrimaryDrawerItem().withName(getString(R.string.wechat)).withIcon(R.drawable.ic_wechat_black_24dp).withIdentifier(2).withSelectable(false),
                        PrimaryDrawerItem().withName(getString(R.string.collect)).withIcon(R.drawable.ic_collect_black_24dp).withIdentifier(3).withSelectable(false),
                        PrimaryDrawerItem().withName(getString(R.string.day_night)).withIcon(R.drawable.ic_daynight_black_24dp).withIdentifier(4).withSelectable(false),
                        PrimaryDrawerItem().withName(getString(R.string.setting)).withIcon(R.drawable.ic_setting_black_24dp).withIdentifier(5).withSelectable(false)
                )
                .withOnDrawerItemClickListener(object : Drawer.OnDrawerItemClickListener {
                    override fun onItemClick(view: View?, position: Int, drawerItem: IDrawerItem<*>): Boolean {
                        if (drawerItem is Nameable<*>) {
                            when (drawerItem.name?.toString()) {
                                getString(R.string.me) -> {

                                }
                                getString(R.string.wechat) -> {
                                    Intent(this@MainActivity, WechatActivity::class.java).run {
                                        startActivity(this)
                                    }
                                }
                                getString(R.string.collect) -> {
                                }
                                getString(R.string.day_night) -> {

                                }
                                getString(R.string.setting) -> {
                                }
                            }
                        }
                        onBackPressed()
                        return false
                    }
                })
                .withShowDrawerOnFirstLaunch(true)
                .build()
        crossfadeDrawerLayout = result.drawerLayout as CrossfadeDrawerLayout
        crossfadeDrawerLayout.setMaxWidthPx(DrawerUIUtils.getOptimalDrawerWidth(this))
        val miniResult = result.miniDrawer!!
        val view = miniResult.build(this)
        view.setBackgroundColor(UIUtils.getThemeColorFromAttrOrRes(this, com.mikepenz.materialdrawer.R.attr.material_drawer_background, com.mikepenz.materialdrawer.R.color.material_drawer_background))
        crossfadeDrawerLayout.smallView.addView(view, ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.MATCH_PARENT)
        miniResult.withCrossFader(object : ICrossfader {

            override val isCrossfaded: Boolean
                get() = crossfadeDrawerLayout.isCrossfaded

            override fun crossfade() {
                val isFaded = isCrossfaded
                if (isFaded) {
                    result.drawerLayout.closeDrawer(GravityCompat.START)
                }
            }
        })
    }

    @SuppressLint("WrongConstant")
    override fun initView() {
        setSupportActionBar(toolbar)
        supportActionBar?.setDisplayHomeAsUpEnabled(true)
        supportActionBar?.setTitle(R.string.home)



        bottom_navigation.run {
            labelVisibilityMode = 1
            setOnNavigationItemSelectedListener(onNavigationItemSelectedListener)
        }

        showFragment(mIndex)
    }

    override fun initData() {
    }

    override fun onSaveInstanceState(_outState: Bundle) {
        var outState = _outState
        if (::result.isInitialized) {
            outState = result.saveInstanceState(outState)
        }
        if (::headerResult.isInitialized) {
            outState = headerResult.saveInstanceState(outState)
        }
        super.onSaveInstanceState(outState)
        _outState?.putInt(BOTTOM_INDEX, mIndex)
    }

    override fun onBackPressed() {
        if (result.isDrawerOpen) {
            result.closeDrawer()
        } else {
            super.onBackPressed()
        }
    }

    /**
     * NavigationItemSelect的监听
     */
    private val onNavigationItemSelectedListener = BottomNavigationView.OnNavigationItemSelectedListener { item ->
        return@OnNavigationItemSelectedListener when (item.itemId) {
            R.id.action_home -> {
                showFragment(FRAGMENT_HOME)
                true
            }
            R.id.action_navigation -> {
                showFragment(FRAGMENT_NAVIGATION)
                true
            }
            R.id.action_knowledge_system -> {
                showFragment(FRAGMENT_KNOWLEDGE)
                true
            }
            R.id.action_project -> {
                showFragment(FRAGMENT_PROJECT)
                true
            }
            else -> {
                false
            }
        }
    }

    private fun showFragment(index: Int) {
        val transaction = supportFragmentManager.beginTransaction()
        hideFragments(transaction)

        mIndex = index
        when (mIndex) {
            FRAGMENT_HOME -> {
                toolbar.title = getString(R.string.home)
                if (mHomeFragment == null) {
                    mHomeFragment = HomeFragment.getInstance()
                    transaction.add(R.id.container, mHomeFragment!!, "home")
                } else {
                    transaction.show(mHomeFragment!!)
                }
            }
            FRAGMENT_NAVIGATION -> {
                toolbar.title = getString(R.string.navigation)
                if (mNavigationFragment == null) {
                    mNavigationFragment = NavigationFragment.getInstance()
                    transaction.add(R.id.container, mNavigationFragment!!, "navigation")
                } else {
                    transaction.show(mNavigationFragment!!)
                }
            }
            FRAGMENT_KNOWLEDGE -> {
                toolbar.title = getString(R.string.knowledge_system)
                if (mKnowledgeTreeFragment == null) {
                    mKnowledgeTreeFragment = KnowledgeTreeFragment.getInstanc()
                    transaction.add(R.id.container, mKnowledgeTreeFragment!!, "knowledge")
                } else {
                    transaction.show(mKnowledgeTreeFragment!!)
                }
            }
            FRAGMENT_PROJECT -> {
                toolbar.title = getString(R.string.project)
                if (mProjectFragment == null) {
                    mProjectFragment = ProjectFragment.getInstance()
                    transaction.add(R.id.container, mProjectFragment!!, "project")
                } else {
                    transaction.show(mProjectFragment!!)
                }
            }


        }
    }

    /**
     * 隐藏所有的Fragment
     */
    private fun hideFragments(transaction: FragmentTransaction) {
        mHomeFragment?.let { transaction.hide(it) }
        mKnowledgeTreeFragment?.let { transaction.hide(it) }
        mNavigationFragment?.let { transaction.hide(it) }
        mProjectFragment?.let { transaction.hide(it) }
    }
}
